package util.converters

import org.codehaus.groovy.grails.web.converters.configuration.ConvertersConfigurationHolder
import org.codehaus.groovy.grails.web.converters.configuration.ConverterConfiguration
import org.codehaus.groovy.grails.web.converters.configuration.DefaultConverterConfiguration
import org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller
import org.codehaus.groovy.grails.web.converters.Converter
import org.codehaus.groovy.grails.web.converters.configuration.ChainedConverterConfiguration

class JSON extends grails.converters.JSON{

  public JSON(Object target) {
    super(target)
  }

  @Override
  protected ConverterConfiguration<grails.converters.JSON> initConfig() {
    ConverterConfiguration config = super.initConfig()
    if(config.getOrderedObjectMarshallers().size() == 0){
      initDefaultMarshallers()
      config = super.initConfig()
    }
    return config
  }

  private void initDefaultMarshallers(){
    List<ObjectMarshaller<grails.converters.JSON>> marshallers = new ArrayList<ObjectMarshaller<grails.converters.JSON>>();
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.ArrayMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.ByteArrayMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.CollectionMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.MapMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.EnumMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.ProxyUnwrappingMarshaller<grails.converters.JSON>());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.DateMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.ToStringBeanMarshaller());

    boolean includeDomainVersion = true;
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.DomainClassMarshaller(includeDomainVersion));
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.GroovyBeanMarshaller());
    marshallers.add(new org.codehaus.groovy.grails.web.converters.marshaller.json.GenericJavaBeanMarshaller());

    DefaultConverterConfiguration<grails.converters.JSON> cfg = new DefaultConverterConfiguration<grails.converters.JSON>(marshallers);
    cfg.setEncoding("UTF-8");
    cfg.setCircularReferenceBehaviour(Converter.CircularReferenceBehaviour.DEFAULT)
    cfg.setPrettyPrint(false);
    ConvertersConfigurationHolder.setDefaultConfiguration(grails.converters.JSON.class, new ChainedConverterConfiguration<grails.converters.JSON>(cfg));
  }
}